import React, { Component } from 'react';
import { Button, Select, Row, Col, Icon } from 'tinper-bee';

import DatePicker from 'bee-datepicker';
import moment from 'moment';
moment.locale('zh-cn');
const format = "YYYY-MM-DD";
import zhCN from "rc-calendar/lib/locale/zh_CN";
import enUS from "rc-calendar/lib/locale/en_US";

import Tooltip from 'bee-tooltip';
import 'bee-tooltip/build/Tooltip.css';
const textOverflowIndex = 10; // 控制项目名称在多少个字符后隐藏

import {
    vendorsGetUrlParam,
    vendorsFmtDate,
    vendorsWarning as warning
} from "../../utils/config";

import {
    BillTypeList,
    BillStatusList,
    fixMuliSelectArrow,
    clearAddedNode
} from './billsInquiry.config';

const Option = Select.Option;

export default class SearchForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
            billType: "请选择",
            pkProject: "请选择",
            creator: [],
            status: [],
            startTime: "",
            endTime: "",
            billTypeDisabled: false, // 单据是否有审批流
            autofocus: false // 制单人列表默认关闭
        }
    }
    setBillType = (billType) => {
        billType = BillTypeList.filter((item) => {
            return item.value == billType
        });
        return JSON.stringify(billType[0])
    };
    setFromGroupQueryData = (fromGroupData) => {
        let startTime = fromGroupData['start_time'] && vendorsFmtDate(Number(fromGroupData['start_time'])) ||'';
        let endTime = fromGroupData['end_time'] && vendorsFmtDate(Number(fromGroupData['end_time']))||'';
        let billType = this.setBillType(fromGroupData['billType']);
        //带入单据类型 判断是否有审批状态下拉
        this.handleBillTypeSelect(billType);
        this.setState({
            startTime,
            endTime,
            billType,
            pkProject: fromGroupData['pkProject'],
            pkOrg: fromGroupData['pk_org'],
        }, () => {
            this.formSearch()
            this.updateSearchData();
        })
    };
    componentDidMount() {
        let _this = this;
        // 解决多选框没有下拉箭头问题
        let multipleSelectArr = document.getElementsByClassName('u-select-selection--multiple');
        fixMuliSelectArrow(multipleSelectArr);

        let target = document.getElementsByClassName('u-select-selection__clear')[0];
        target.addEventListener("click", _this.clearPkProject);



        let fromGroupData = JSON.parse(sessionStorage.getItem('fromGroupData'));
        let startPage = vendorsGetUrlParam(decodeURI(window.location.href));
        startPage = Object.keys(startPage);
        if (fromGroupData && startPage && startPage.length) {
            let keysFromGroup = Object.keys(fromGroupData);
            if (keysFromGroup && keysFromGroup.length) {
                this.setFromGroupQueryData(fromGroupData)
            }
        }
    }

    // 清空项目选择框方法
    clearPkProject = () => {
        this.setState({
            pkProject: "请选择"
        });
    }

    componentWillReceiveProps(nextProps) {
        // 修改选择组织后，清空项目列表
        if (this.props.orgName !== nextProps.orgName && this.props.orgName !== "默认组织名称") {
            this.setState({
                pkProject: "请选择"
            }, () => {
                this.updateSearchData();
            });
        }
    }

    componentWillUnmount() {
        let _this = this;
        // 移除componentDidMount中手动创建的node节点
        clearAddedNode();
        // 移除监听
        let target = document.getElementsByClassName('u-select-selection__clear')[0];
        target.removeEventListener("click", _this.clearPkProject);
    }

    //选择单据类型
    handleBillTypeSelect = (value) => {
        let _this = this;
        let { isApproval } = JSON.parse(value);
        if (isApproval) {
            this.setState({
                billType: value,
                billTypeDisabled: isApproval
            }, callback);
        } else {
            this.setState({
                billType: value,
                billTypeDisabled: isApproval,
                status: []
            }, callback);
        }

        function callback() {
            _this.updateSearchData();
        }

    }

    //选择项目
    handleProjectSelect = (value) => {
        let divNode = document.getElementsByClassName('u-select-selection-selected-value')[1]; // 清空下拉框的鼠标hover时候的title值
		setTimeout(() => {
			divNode.setAttribute("title", "");
		}, 500);
        this.setState({
            pkProject: value
        }, () => {
            this.updateSearchData();
        });
    }

    //选择制单人
    handleManagerSelect = (value) => {
        let managerArr = [...this.state.creator];
        managerArr.push(value);
        this.setState({
            creator: managerArr
        }, () => {
            this.updateSearchData()
        });
    }

    //清除某个制单人
    handleManagerDelSelect = (value) => {
        let managerArr = [...this.state.creator];
        let index = managerArr.indexOf(value);
        managerArr.splice(index, 1);
        this.setState({
            creator: managerArr
        }, () => {
            this.updateSearchData();
        });
    }

    //选择审批状态
    handleBillStatusSelect = (value) => {
        let billStatusArr = [...this.state.status];
        billStatusArr.push(value);
        this.setState({
            status: billStatusArr
        }, () => {
            this.updateSearchData();
        });
    }

    //清除某个审批状态
    handleBillStatusDelSelect = (value) => {
        let billStatusArr = [...this.state.status];
        let index = billStatusArr.indexOf(value);
        billStatusArr.splice(index, 1);
        this.setState({
            status: billStatusArr
        }, () => {
            this.updateSearchData();
        });
    }

    //选择开始时间
    selectStartTime = (value) => {
        if (value !== null) {
            let { _d } = value;
            if (this.state.endTime !== "") {
                if (new Date(_d).getTime() > new Date(this.state.endTime).getTime()) {
                    warning({ text: "起始日期不得大于结束日期" });
                    this.setState({
                        startTime: this.state.startTime
                    });
                } else {
                    this.setState({
                        startTime: _d
                    });
                }
            } else {
                this.setState({
                    startTime: _d
                });
            }
        } else {
            this.setState({ startTime: "" }, () => {this.updateSearchData()});
        }
    }

    //选择结束时间
    selectEndTime = (value) => {
        if (value !== null) {
            let { _d } = value;
            if (this.state.startTime !== "") {
                if (new Date(_d).getTime() < new Date(this.state.startTime).getTime()) {
                    warning({ text: "结束日期不得小于起始日期" });
                    this.setState({
                        endTime: this.state.endTime
                    }, () => {this.updateSearchData();});
                } else {
                    this.setState({
                        endTime: _d
                    }, () => {this.updateSearchData();});
                }
            } else {
                this.setState({
                    endTime: _d
                }, () => {this.updateSearchData();});
            }
        } else {
            this.setState({ endTime: "" }, () => {this.updateSearchData()});
        }
    }

    //清空表单
    formClear = () => {
        this.setState({
            billType: "请选择",
            pkProject: "请选择",
            creator: [],
            status: [],
            startTime: "",
            endTime: ""
        }, () => {this.updateSearchData();});
    }

    //搜索表单
    formSearch = () => {
        let searchData = this.getPostData();
        this.props.searchBillList(searchData);
    }

    // 更新搜索数据
    updateSearchData = () => {
        let postData = this.getPostData();
        this.props.setSearchParams(postData);
    }

    // 获取搜索数据
    getPostData = () => {
        let today = vendorsFmtDate(new Date().getTime());
        let billStatusArr = this.state.status.map((item) => {
            return JSON.parse(item).key;
        });
        let searchData = {
            billType: this.state.billType === '请选择' ? null : JSON.parse(this.state.billType).key, 
            pkProject: this.state.pkProject === '请选择' ? null : [this.state.pkProject],
            creators: this.state.creator,
            billStatus: this.state.status.length === 0 ? [] : billStatusArr,
            startTime: !this.state.startTime ? "1000-01-01" : vendorsFmtDate(this.state.startTime),
            endTime: !this.state.endTime? today : vendorsFmtDate(this.state.endTime)
        };
        return searchData;
    }

    // 下拉框选项工厂
    optionsFactory = (list) => {
        return list.map(item => {
            return (
                <Option value={JSON.stringify(item)}>{item.value}</Option>
            )
        })
    }

    // 制单人获取焦点时，获取制单人列表
    creatorsFormFocus = () => {
        let pkPro = this.state.pkProject;
        this.props.getCreators(pkPro);
    };

    render() {
        return (
            <div className="bill-body-form margin-top10">
                <Row className="bill-body-form-row">
                    <Col md={4}>
                        <span className="inline-block">
                            <Icon className="bill-body-form-mi" type="uf-mi" />单据类型 ：</span>
                        <Select
                            className="bill-body-form-select inline-block"
                            value={this.state.billType}
                            onSelect={this.handleBillTypeSelect}>
                            {this.optionsFactory(BillTypeList)}
                        </Select>
                    </Col>
                    <Col md={4}>
                        <span className="inline-block">项目名称 ：</span>
                        <Select
                            showSearch
                            optionFilterProp="name"
                            notFoundContent="没有相关条目"
                            className="bill-body-form-select inline-block"
                            value={this.state.pkProject}
                            allowClear={'allowClear'}
                            onSelect={this.handleProjectSelect}>
                            {this.props.proList.map((item) => {
                                let text = item.sname;
                                let displayText = text.length > textOverflowIndex ? text.substr(0, textOverflowIndex) + "..." : text;
                                return (
                                    <Option value={item.pkProject} name={item.sname}>
                                        <Tooltip
                                            className={[text.length > textOverflowIndex ? "show" : "hidden"]}
                                            inverse
                                            placement="top"
                                            overlay={text}>
                                            <div>{displayText}</div>
                                        </Tooltip>
                                    </Option>
                                )
                            })}
                        </Select>
                    </Col>
                    <Col md={4}>
                        <span className="inline-block">制单人 ：</span>
                        <Select
                            className="bill-body-form-select inline-block"
                            value={this.state.creator}
                            multiple={true}
                            placeholder="请选择"
                            onFocus={this.creatorsFormFocus}
                            onSelect={this.handleManagerSelect}
                            onDeselect={this.handleManagerDelSelect}>
                            {this.props.creators.map((item) => {
                                return (
                                    <Option value={item.userId}>{item.userName}</Option>
                                )
                            })}
                        </Select>
                    </Col>
                </Row>
                <Row>
                    <Col md={4}>
                        <span className="inline-block">审批状态 ：</span>
                        <Select
                            className="bill-body-form-select inline-block"
                            value={this.state.status}
                            multiple={true}
                            placeholder="请选择"
                            disabled={this.state.billTypeDisabled ? "" : "disabled"}
                            onSelect={this.handleBillStatusSelect}
                            onDeselect={this.handleBillStatusDelSelect}>
                            {this.optionsFactory(BillStatusList)}
                        </Select>
                    </Col>
                    <div className="fl margin-left-15">
                        <span className="bill-body-form-date-label">制单时间 ：</span>
                        <div className="inline-block-format">
                            <DatePicker
                                format={format}
                                showToday={false}
                                onChange={this.selectStartTime}
                                locale={zhCN}
                                placeholder="年/月/日"
                                value={this.state.startTime === "" ? "" : moment(this.state.startTime)}
                                className="bill-body-form-date inline-block-format"
                            />
                        </div>
                        <span className="bill-body-form-date-label">至</span>
                        <div className="inline-block-format">
                            <DatePicker
                                format={format}
                                showToday={false}
                                onChange={this.selectEndTime}
                                locale={zhCN}
                                placeholder="年/月/日"
                                value={this.state.endTime === "" ? "" : moment(this.state.endTime)}
                                className="bill-body-form-date inline-block-format"
                            />
                        </div>
                    </div>
                    <div className="fr" style={{ marginRight: 90 }}>
                        <Button
                            className="bill-body-form-btn-clear bg-grey-200"
                            onClick={this.formClear}>清空重置</Button>
                        <Button
                            colors="primary"
                            size={'sm'}
                            onClick={this.formSearch}>搜索</Button>
                    </div>
                </Row>
            </div>
        );
    }
}